﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.ComponentModel;
using System.Collections;
using System.Configuration;
using OneMG.Phoenix.Kernel.Enum;

namespace OneMG.Phoenix.Kernel.Helper
{
	public class ImageHelper
    {

        #region 删除文件

        /// <summary>
        /// 删除文件以及生成的缩略图
        /// </summary>
        /// <param name="filePath">文件的相对路径</param>
        public static void  DeleteFile(string filePath)
        {
            //System.Web.HttpContext.Current.Server.MapPath(sUploadDir)

            //文件全名称
            string sOriginalFileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
            //文件扩展名
            string sFileExt = sOriginalFileName.Substring(sOriginalFileName.LastIndexOf(".") + 1).ToLower();

            //文件完整路径
            string fullPath = System.Web.HttpContext.Current.Server.MapPath(filePath);

            //删除原始文件

            File.Delete(fullPath);

            //删除缩略图
            File.Delete(fullPath + "-100-100." + sFileExt);


        }

        #endregion

        #region 保存上传文件
        /// <summary>
		/// 处理单个文件上传
		/// </summary>
		/// <param name="postedFile">post文件</param>
		/// <param name="sUploadPath">上传文件路径</param>
		/// <returns>上传成功的文件路径</returns>
		public static string UploadFile(HttpPostedFile postedFile, string sUploadPath)
		{
			//上传源文件全名称
			string sOriginalFileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf("\\") + 1);
			//上传文件扩展名
			string sFileExt = sOriginalFileName.Substring(sOriginalFileName.LastIndexOf(".") + 1).ToLower();

			//随机文件名
			string sSaveFileName = RandomHelper.GetDistinctFileName(sFileExt);

			//如果不存在则建立新目录
			string sUploadDir = System.IO.Path.Combine(sUploadPath, FileHelper.GetDirectoryByTime("3"));//虚拟路径
			string sFullPath = sUploadDir + "/" + sSaveFileName;

			FileHelper.CreateFolderIfNotExist(System.Web.HttpContext.Current.Server.MapPath(sUploadDir));

            //保存上传文件
			postedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath(sFullPath));

			//如果文件存在
			if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(sFullPath)))
			{
				sFullPath = "";
			}
			return sFullPath;
		}
		#endregion

		#region 生成缩略图
		static Hashtable htmimes = new Hashtable();
		internal readonly string AllowExt = ".jpe|.jpeg|.jpg|.gif|.png|.tif|.tiff|.bmp|.swf";//允许处理的图片类型

		/// <summary>
		/// 生成缩略图
		/// </summary>
		/// <param name="fileStream">文件流</param>
		/// <param name="thumImagePath">生成的缩略图的文件路径</param>
		/// <param name="thumImageWidth">缩略图的宽度</param>
		/// <param name="thumImageHeight">缩略图的宽度</param>
		public static void ToThumbnailImages(Stream fileStream, string thumImagePath, int thumImageWidth, int thumImageHeight)
		{
			ToThumbnailImages(fileStream, thumImagePath, thumImageWidth, thumImageHeight, BaseEnum.ImageThumMode.None);
		}


        public static string ToThumImages(string sourceImagePath, int thumImageWidth, int thumImageHeight)
        {

            //上传文件扩展名
            string sFileExt = sourceImagePath.Substring(sourceImagePath.LastIndexOf(".") + 1).ToLower();

            string thumImagePath = sourceImagePath + "-" + thumImageWidth.ToString() + "-" + thumImageHeight.ToString() + "." + sFileExt;

            ToThumbnailImages(sourceImagePath, thumImagePath, thumImageWidth, thumImageHeight, BaseEnum.ImageThumMode.None, false);
            return thumImagePath;
        }


		/// <summary>
		/// 生成缩略图
		/// </summary>
		/// <param name="fileStream">文件流</param>
		/// <param name="thumImagePath">生成的缩略图的文件路径</param>
		/// <param name="thumImageWidth">缩略图的宽度</param>
		/// <param name="thumImageHeight">缩略图的宽度</param>
		/// <param name="imageThumMode">压缩模式</param>
		public static void ToThumbnailImages(Stream fileStream, string thumImagePath, int thumImageWidth, int thumImageHeight, BaseEnum.ImageThumMode imageThumMode)
		{
			htmimes[".jpe"] = "image/jpeg";
			htmimes[".jpeg"] = "image/jpeg";
			htmimes[".jpg"] = "image/jpeg";
			htmimes[".gif"] = "image/gif";
			htmimes[".png"] = "image/png";
			htmimes[".tif"] = "image/tiff";
			htmimes[".tiff"] = "image/tiff";
			htmimes[".bmp"] = "image/bmp";
			htmimes[".swf"] = "image/swf";

			//调用生成缩略图方法
			ImageHelper toImg = new ImageHelper();
			toImg.ToThumImages(fileStream, thumImagePath, thumImageWidth, thumImageHeight, imageThumMode);
		}

		/// <summary>
		/// 生成缩略图(得到原图灰色图)
		/// </summary>
		/// <param name="sourceImagePath">原图片路径(相对路径)</param>
		/// <param name="thumImagePath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>
		/// <param name="IsGrayMap">是否是灰色图</param>
		public static void ToThumbnailImages(string sourceImagePath, string thumImagePath, bool IsGrayMap)
		{
			ToThumbnailImages(sourceImagePath, thumImagePath, -1, -1, BaseEnum.ImageThumMode.None, IsGrayMap);
		}

		/// <summary>
		/// 生成缩略图(得到自动适应的缩微图)
		/// </summary>
		/// <param name="sourceImagePath">原图片路径(相对路径)</param>
		/// <param name="thumImagePath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>
		/// <param name="thumImageWidth">缩略图的宽度</param>
		/// <param name="thumImageHeight">缩略图的宽度</param>
		public static void ToThumbnailImages(string sourceImagePath, string thumImagePath, int thumImageWidth, int thumImageHeight)
		{
			ToThumbnailImages(sourceImagePath, thumImagePath, thumImageWidth, thumImageHeight, false);
		}

		/// <summary>
		/// 生成缩略图(得到自动适应的缩微图,包括可以得到灰色图)
		/// </summary>
		/// <param name="sourceImagePath">原图片路径(相对路径)</param>
		/// <param name="thumImagePath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>
		/// <param name="thumImageWidth">缩略图的宽度</param>
		/// <param name="thumImageHeight">缩略图的宽度</param>
		/// <param name="IsGrayMap">是否是灰色图</param>
		public static void ToThumbnailImages(string sourceImagePath, string thumImagePath, int thumImageWidth, int thumImageHeight, bool IsGrayMap)
		{
			ToThumbnailImages(sourceImagePath, thumImagePath, thumImageWidth, thumImageHeight, BaseEnum.ImageThumMode.None, IsGrayMap);
		}

		/// <summary>
		/// 生成缩略图(得到对应模式的缩微图)
		/// </summary>
		/// <param name="sourceImagePath">原图片路径(相对路径)</param>
		/// <param name="thumImagePath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>
		/// <param name="thumImageWidth">缩略图的宽度</param>
		/// <param name="thumImageHeight">缩略图的宽度</param>
		/// <param name="imageThumMode">缩略图模式</param>
		public static void ToThumbnailImages(string sourceImagePath, string thumImagePath, int thumImageWidth, int thumImageHeight, BaseEnum.ImageThumMode imageThumMode)
		{
			ToThumbnailImages(sourceImagePath, thumImagePath, thumImageWidth, thumImageHeight, imageThumMode, false);
		}

		/// <summary>
		/// 生成缩略图(得到对应模式的缩微图,包括可以得到灰色图)
		/// </summary>
		/// <param name="sourceImagePath">原图片路径(相对路径)</param>
		/// <param name="thumImagePath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>
		/// <param name="thumImageWidth">缩略图的宽度</param>
		/// <param name="thumImageHeight">缩略图的宽度</param>
		/// <param name="imageThumMode">缩略图模式</param>
		/// <param name="IsGrayMap">是否是灰色图</param>
		public static void ToThumbnailImages(string sourceImagePath, string thumImagePath, int thumImageWidth, int thumImageHeight, BaseEnum.ImageThumMode imageThumMode, bool IsGrayMap)
		{
			htmimes[".jpe"] = "image/jpeg";
			htmimes[".jpeg"] = "image/jpeg";
			htmimes[".jpg"] = "image/jpeg";
			htmimes[".gif"] = "image/gif";
			htmimes[".png"] = "image/png";
			htmimes[".tif"] = "image/tiff";
			htmimes[".tiff"] = "image/tiff";
			htmimes[".bmp"] = "image/bmp";
			htmimes[".swf"] = "image/swf";

			//调用生成缩略图方法
			ImageHelper toImg = new ImageHelper();
			toImg.ToThumImages(sourceImagePath, thumImagePath, thumImageWidth, thumImageHeight, imageThumMode, IsGrayMap);
		}
		#endregion

		#region 复制到指定的目录(转移图片)
		/// <summary>
		/// 复制到指定目录
		/// </summary>
		/// <param name="SourceImagePath"></param>
		/// <param name="sNewPath"></param>
		public static void ToCopyImages(string SourceImagePath, string sNewPath)
		{
			//从 原图片 创建 Image 对象
			System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(SourceImagePath));
			try
			{
				//将此 原图片 以指定格式并用指定的编解码参数保存到指定文件	
				string savePath = HttpContext.Current.Server.MapPath(sNewPath);
				//从原图片的路径中取得所在目录
				string saveDir = savePath.Substring(0, savePath.LastIndexOf("\\") + 1);
				//检查目录是否存在,不存在并创建目录
				FileHelper.CreateFolderIfNotExist(saveDir);
				image.Save(savePath);
			}
			catch (System.Exception e)
			{
				throw e;
			}
			finally
			{
				image.Dispose();
			}
		}
		#endregion

		#region 获取图像编码解码器的所有相关信息
		/// <summary>
		/// 获取图像编码解码器的所有相关信息
		/// </summary>
		/// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>
		/// <returns>返回图像编码解码器的所有相关信息</returns>
		protected static ImageCodecInfo GetCodecInfo(string mimeType)
		{
			ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
			foreach (ImageCodecInfo ici in CodecInfo)
			{
				if (ici.MimeType == mimeType) return ici;
			}
			return null;
		}
		#endregion

        #region 检测扩展名的有效性
        /// <summary>
		/// 检测扩展名的有效性
		/// </summary>
		/// <param name="sExt">文件名扩展名</param>
		/// <returns>如果扩展名有效,返回true,否则返回false.</returns>
		bool CheckValidExt(string sExt)
		{
			bool flag = false;
			string[] aExt = AllowExt.Split('|');
			foreach (string filetype in aExt)
			{
				if (filetype.ToLower() == sExt)
				{
					flag = true;
					break;
				}
			}
			return flag;
		}
		#endregion

		#region 保存图片
		/// <summary>
		/// 保存图片
		/// </summary>
		/// <param name="image">Image 对象</param>
		/// <param name="srcImage">源Image 对象</param>
		/// <param name="savePath">保存路径</param>
		/// <param name="ici">指定格式的编解码参数</param>
		void SaveImage(System.Drawing.Image image, System.Drawing.Image srcImage, string savePath, ImageCodecInfo ici)
		{
			//从图片的路径中取得所在目录
			string saveDir = savePath.Substring(0, savePath.LastIndexOf("\\") + 1);
			//检查目录是否存在,不存在并创建目录
			FileHelper.CreateFolderIfNotExist(saveDir);
			if (srcImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif))
			{
				OctreeQuantizer qtz = new OctreeQuantizer(255, 8);
				Bitmap gifImg = qtz.Quantize(image);

				gifImg.Save(savePath, System.Drawing.Imaging.ImageFormat.Gif);
			}
			else
			{
				//设置 原图片 对象的 EncoderParameters 对象
				EncoderParameters parameters = new EncoderParameters();
				long[] quality = new long[1];
				quality[0] = 100;
				parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);

				if (ici != null)
					image.Save(savePath, ici, parameters);
				else
					image.Save(savePath, srcImage.RawFormat);

				parameters.Dispose();
			}
		}
		#endregion

		#region 生成缩略图
		/// <summary>
		/// 生成缩略图
		/// </summary>
		/// <param name="fileStream">文件流</param>
		/// <param name="thumImagePath">生成的缩略图的文件路径</param>
		/// <param name="thumImageWidth">缩略图的宽度</param>
		/// <param name="thumImageHeight">缩略图的宽度</param>
		/// <param name="imageThumMode">压缩模式</param>
		protected void ToThumImages(Stream fileStream, string thumImagePath, int thumImageWidth, int thumImageHeight, BaseEnum.ImageThumMode imageThumMode)
		{
			string ThumImagePath = thumImagePath;
			if (fileStream == null) throw new NullReferenceException("图片源文件参数为空！");

			//从 原图片 创建 Image 对象
			System.Drawing.Image image = System.Drawing.Image.FromStream(fileStream, true);

			//求实际的宽度和长度
			int ThumImageWidth = thumImageWidth;
			int ThumImageHeight = thumImageHeight;
			if (ThumImageWidth == -1)
				ThumImageWidth = image.Width;
			if (ThumImageHeight == -1)
				ThumImageHeight = image.Height;
			int width = image.Width;
			int height = image.Height;
			int newWidth = 0;
			int newHeight = 0;

			#region-- 得到宽高的逻辑
			switch (imageThumMode)
			{
				case BaseEnum.ImageThumMode.FixHeight:
					newHeight = ThumImageHeight;
					newWidth = ((width * newHeight) / height);
					ThumImageWidth = newWidth;
					break;

				case BaseEnum.ImageThumMode.FixWeight:
					newWidth = ThumImageWidth;
					newHeight = ((height * newWidth) / width);
					ThumImageHeight = newHeight;
					break;

				case BaseEnum.ImageThumMode.FixWeightAndHeight:
					if (width / height > ThumImageWidth / ThumImageHeight)
					{
						newWidth = ThumImageWidth;
						newHeight = ((height * newWidth) / width);
					}
					else
					{
						newHeight = ThumImageHeight;
						newWidth = ((width * newHeight) / height);
					}
					break;

				case BaseEnum.ImageThumMode.LimitHeight:
					if (height > ThumImageHeight)
					{
						newHeight = ThumImageHeight;
						newWidth = ((width * newHeight) / height);
						ThumImageWidth = newWidth;
					}
					else
					{
						newHeight = height;
						newWidth = width;
					}
					break;

				case BaseEnum.ImageThumMode.LimitWeight:
					if (width > ThumImageWidth)
					{
						newWidth = ThumImageWidth;
						newHeight = ((height * newWidth) / width);
						ThumImageHeight = newHeight;
					}
					else
					{
						newHeight = height;
						newWidth = width;
					}
					break;

				case BaseEnum.ImageThumMode.LimitHeightAndHeight:
					if (width > 0 && height > 0)
					{
						var rate = ((double)ThumImageWidth / (double)width < (double)ThumImageHeight / (double)height) ? (double)ThumImageWidth / (double)width : (double)ThumImageHeight / (double)height;
						//如果 指定高度/图片高度  小于  指定宽度/图片宽度 ，  那么，我们的比例数 取 指定高度/图片高度。
						//如果 指定高度/图片高度  大于  指定宽度/图片宽度 ，  那么，我们的比例数 取 指定宽度/图片宽度。
						if (rate <= 1)
						{
							newWidth = (int)((double)width * rate); //图片新的宽度 = 宽度 * 比例数
							newHeight = (int)((double)height * rate);
						}
						else
						{//  如果比例数大于1，则新的宽度等于以前的宽度。
							newWidth = width;
							newHeight = height;
						}
					}
					break;

				case BaseEnum.ImageThumMode.Fill:
				case BaseEnum.ImageThumMode.None:
					newWidth = ThumImageWidth;
					newHeight = ThumImageHeight;
					break;

			}
			#endregion

			if (ThumImageWidth < 1 || ThumImageHeight < 1 || newWidth < 1 || newHeight < 1)
			{
				return;
			}

			//用指定的大小和格式初始化 Bitmap 类的新实例
			string sExt = ThumImagePath.Substring(ThumImagePath.LastIndexOf(".")).ToLower();
			Bitmap bitmap = new Bitmap(ThumImageWidth, ThumImageHeight, PixelFormat.Format32bppArgb);
			//从指定的 Image 对象创建新 Graphics 对象
			Graphics graphics = Graphics.FromImage(bitmap);
			//设置高质量插值法
			graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
			//设置高质量,低速度呈现平滑程度
			graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

			graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
			graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

			graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

			//清除整个绘图面并以透明背景色填充
			if (sExt.ToLower().Trim() == ".jpe" || sExt.ToLower().Trim() == ".jpeg" || sExt.ToLower().Trim() == ".jpg")
				graphics.Clear(Color.White);
			else
				graphics.Clear(Color.Transparent);

			//在指定位置并且按指定大小绘制 原图片 对象
			graphics.DrawImage(image, new Rectangle((ThumImageWidth - newWidth) / 2, (ThumImageHeight - newHeight) / 2, newWidth, newHeight));

			try
			{
				//将此 原图片 以指定格式并用指定的编解码参数保存到指定文件
				this.SaveImage(bitmap, image, ThumImagePath, GetCodecInfo((string)htmimes[sExt]));
			}
			catch (System.Exception e)
			{
				throw e;
			}
			finally
			{
				image.Dispose();
				bitmap.Dispose();
				graphics.Dispose();
			}
		}


		/// <summary>
		/// 生成缩略图
		/// </summary>
		/// <param name="sourceImagePath">原图片路径(相对路径)</param>
        /// <param name="thumImagePath">生成的缩略图路径(相对路径)</param>
		/// <param name="thumImageWidth">缩略图的宽度</param>
		/// <param name="thumImageHeight">缩略图的高度</param>
		/// <param name="imageThumMode">压缩模式</param>
		/// <param name="isGrayMap">是否是灰色图</param>
		protected void ToThumImages(string sourceImagePath, string thumImagePath, int thumImageWidth, int thumImageHeight,
			BaseEnum.ImageThumMode imageThumMode, bool isGrayMap)
		{
            string SourceImagePath = System.Web.HttpContext.Current.Server.MapPath(sourceImagePath);

			string ThumImagePath = System.Web.HttpContext.Current.Server.MapPath(thumImagePath);

            string sExt = SourceImagePath.Substring(SourceImagePath.LastIndexOf(".")).ToLower();

			if (SourceImagePath == null ||
				SourceImagePath.ToString() == System.String.Empty) throw new NullReferenceException("图片源文件参数为空！");

            //System.Web.HttpContext.Current.Server.MapPath(SourceImagePath)
			if (!System.IO.File.Exists(SourceImagePath)) throw new FileNotFoundException("图片源文件(" + SourceImagePath + ")不存在！");

			if (!CheckValidExt(sExt))
			{
				throw new ArgumentException("原图片文件格式不正确,支持的格式有[ " + AllowExt + " ]", "SourceImagePath");
			}

			//从 原图片 创建 Image 对象
			System.Drawing.Image image = System.Drawing.Image.FromFile(SourceImagePath, true);

			//求实际的宽度和长度
			int ThumImageWidth = thumImageWidth;
			int ThumImageHeight = thumImageHeight;
			if (ThumImageWidth == -1)
				ThumImageWidth = image.Width;
			if (ThumImageHeight == -1)
				ThumImageHeight = image.Height;
			int width = image.Width;
			int height = image.Height;
			int newWidth = 0;
			int newHeight = 0;

			#region-- 得到宽高的逻辑
			switch (imageThumMode)
			{
				case BaseEnum.ImageThumMode.FixHeight:
					newHeight = ThumImageHeight;
					newWidth = ((width * newHeight) / height);
					ThumImageWidth = newWidth;
					break;

				case BaseEnum.ImageThumMode.FixWeight:
					newWidth = ThumImageWidth;
					newHeight = ((height * newWidth) / width);
					ThumImageHeight = newHeight;
					break;

				case BaseEnum.ImageThumMode.FixWeightAndHeight:
					if (width / height > ThumImageWidth / ThumImageHeight)
					{
						newWidth = ThumImageWidth;
						newHeight = ((height * newWidth) / width);
					}
					else
					{
						newHeight = ThumImageHeight;
						newWidth = ((width * newHeight) / height);
					}
					break;

				case BaseEnum.ImageThumMode.LimitHeight:
					if (height > ThumImageHeight)
					{
						newHeight = ThumImageHeight;
						newWidth = ((width * newHeight) / height);
						ThumImageWidth = newWidth;
					}
					else
					{
						newHeight = height;
						newWidth = width;
					}
					break;

				case BaseEnum.ImageThumMode.LimitWeight:
					if (width > ThumImageWidth)
					{
						newWidth = ThumImageWidth;
						newHeight = ((height * newWidth) / width);
						ThumImageHeight = newHeight;
					}
					else
					{
						newHeight = height;
						newWidth = width;
					}
					break;

				case BaseEnum.ImageThumMode.LimitHeightAndHeight:
					if (width / height > ThumImageWidth / ThumImageHeight)
					{
						if (width > ThumImageWidth)
						{
							newWidth = ThumImageWidth;
							newHeight = ((height * newWidth) / width);
							ThumImageHeight = newHeight;
						}
						else
						{
							newHeight = height;
							newWidth = width;
						}
					}
					else
					{
						if (height > ThumImageHeight)
						{
							newHeight = ThumImageHeight;
							newWidth = ((width * newHeight) / height);
							ThumImageWidth = newWidth;
						}
						else
						{
							newHeight = height;
							newWidth = width;
						}
					}
					break;

				case BaseEnum.ImageThumMode.Fill:
				case BaseEnum.ImageThumMode.None:
					newWidth = ThumImageWidth;
					newHeight = ThumImageHeight;
					break;

			}
			#endregion

			if (ThumImageWidth < 1 || ThumImageHeight < 1 || newWidth < 1 || newHeight < 1)
			{
				return ;
			}

			Bitmap orgBitMap = null;
			if (isGrayMap)
			{
				//灰度处理
				orgBitMap = new Bitmap(image);
				DrawForGrapMap(orgBitMap);
				image = System.Drawing.Image.FromHbitmap(orgBitMap.GetHbitmap());
			}

			//用指定的大小和格式初始化 Bitmap 类的新实例
			string savepath = (ThumImagePath == null ? SourceImagePath : ThumImagePath);
			Bitmap bitmap = new Bitmap(ThumImageWidth, ThumImageHeight, PixelFormat.Format32bppArgb);
			//从指定的 Image 对象创建新 Graphics 对象
			Graphics graphics = Graphics.FromImage(bitmap);

			//设置高质量插值法
			graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
			//设置高质量,低速度呈现平滑程度
			graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

			graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
			graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

			graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

			//清除整个绘图面并以透明背景色填充
			if (sExt.ToLower().Trim() == ".jpe" || sExt.ToLower().Trim() == ".jpeg" || sExt.ToLower().Trim() == ".jpg")
				graphics.Clear(Color.White);
			else
				graphics.Clear(Color.Transparent);

			//在指定位置并且按指定大小绘制 原图片 对象
			graphics.DrawImage(image, new Rectangle((ThumImageWidth - newWidth) / 2, (ThumImageHeight - newHeight) / 2, newWidth, newHeight));

			try
			{
				//将此 原图片 以指定格式并用指定的编解码参数保存到指定文件	
				this.SaveImage(bitmap, image, savepath, GetCodecInfo((string)htmimes[sExt]));
			}
			catch (System.Exception e)
			{
				throw e;
			}
			finally
			{
				if (orgBitMap != null) orgBitMap.Dispose();
				image.Dispose();
				bitmap.Dispose();
				graphics.Dispose();
			}
		}
		#endregion

		#region 缩略图
		/// <summary>
		/// 缩略图
		/// </summary>
		/// <param name="ImgFile">原图文件地址</param>
		/// <param name="sImgPath">缩略图保存地址</param>
		/// <param name="ResizeWidth">缩略图宽度</param>
		/// <param name="ResizeHeight">缩略图高度</param>
		/// <param name="BgColor">缩略图背景颜色,注意,背景颜色只能指定KnownColor中的值,如blue,red,green等</param>
		public static void ResizeImg(string ImgFile, string sImgPath, int ResizeWidth, int ResizeHeight, string BgColor)
		{
			try
			{
				FileStream fs = new FileStream(ImgFile, FileMode.Open);
				BinaryReader br = new BinaryReader(fs);
				byte[] bytes = br.ReadBytes((int)fs.Length);
				br.Close();
				fs.Close();
				MemoryStream ms = new MemoryStream(bytes);

				System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(ms);

				//System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(ImgFile);

				int imgPhotoWidth = imgPhoto.Width;
				int imgPhotoHeight = imgPhoto.Height;
				int startX = 0;
				int StartY = 0;
				int NewWidth = 0;
				int NewHeight = 0;

				if (imgPhotoWidth >= ResizeWidth && imgPhotoHeight >= ResizeHeight)
				{
					NewWidth = ResizeWidth;
					NewHeight = Convert.ToInt32(imgPhotoHeight * Math.Round(Convert.ToDecimal(ResizeWidth) / Convert.ToDecimal(imgPhotoWidth), 10));
					startX = 0;
					StartY = (ResizeHeight - NewHeight) / 2;
				}

				if (ResizeWidth > imgPhotoWidth && ResizeHeight < imgPhotoHeight)
				{
					NewHeight = ResizeHeight;
					NewWidth = Convert.ToInt32(imgPhotoWidth * Math.Round(Convert.ToDecimal(ResizeHeight) / Convert.ToDecimal(imgPhotoHeight), 10));
					startX = (ResizeWidth - NewWidth) / 2;
					StartY = 0;
				}

				if (ResizeWidth < imgPhotoWidth && ResizeHeight > imgPhotoHeight)
				{
					NewWidth = ResizeWidth;
					NewHeight = Convert.ToInt32(imgPhotoHeight * Math.Round(Convert.ToDecimal(ResizeWidth) / Convert.ToDecimal(imgPhotoWidth), 10));
					startX = 0;
					StartY = (ResizeHeight - NewHeight) / 2;
				}

				if (imgPhotoWidth < ResizeWidth && imgPhotoHeight < ResizeHeight)
				{
					NewWidth = imgPhotoWidth;
					NewHeight = imgPhotoHeight;
					startX = (ResizeWidth - imgPhotoWidth) / 2;
					StartY = (ResizeHeight - imgPhotoHeight) / 2;
				}

				//计算缩放图片尺寸

				Bitmap bmPhoto = new Bitmap(ResizeWidth, ResizeHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
				bmPhoto.SetResolution(72, 72);
				Graphics gbmPhoto = Graphics.FromImage(bmPhoto);
				gbmPhoto.Clear(Color.FromName(BgColor));
				gbmPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
				gbmPhoto.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

				gbmPhoto.DrawImage(
					  imgPhoto
					, new Rectangle(startX, StartY, NewWidth, NewHeight)
					, new Rectangle(0, 0, imgPhotoWidth, imgPhotoHeight)
					, GraphicsUnit.Pixel
					);
				bmPhoto.Save(sImgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
				imgPhoto.Dispose();
				gbmPhoto.Dispose();
				bmPhoto.Dispose();
			}
			catch (Exception err)
			{
				throw err;
			}
		}
		#endregion

		#region 图片剪切
		/// <summary>
		/// 图片剪切
		/// </summary>
		/// <param name="ImgFile">原图文件地址</param>
		/// <param name="sImgPath">缩略图保存地址</param>
		/// <param name="PointX">剪切起始点 X坐标</param>
		/// <param name="PointY">剪切起始点 Y坐标</param>
		/// <param name="CutWidth">剪切宽度</param>
		/// <param name="CutHeight">剪切高度</param>
		public static void CutImg(string ImgFile, string sImgPath, int PointX, int PointY, int CutWidth, int CutHeight)
		{
			try
			{
				FileStream fs = new FileStream(ImgFile, FileMode.Open);
				BinaryReader br = new BinaryReader(fs);
				byte[] bytes = br.ReadBytes((int)fs.Length);
				br.Close();
				fs.Close();
				MemoryStream ms = new MemoryStream(bytes);

				System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(ms);

				//System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(ImgFile);
				//此处只能用filestream，用 System.Drawing.Image则会报多过进程访问文件的错误，会锁定文件

				Bitmap bmPhoto = new Bitmap(CutWidth, CutHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
				bmPhoto.SetResolution(72, 72);
				Graphics gbmPhoto = Graphics.FromImage(bmPhoto);
				gbmPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
				gbmPhoto.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

				gbmPhoto.DrawImage(
					  imgPhoto
					, new Rectangle(0, 0, CutWidth, CutHeight)
					, new Rectangle(PointX, PointY, CutHeight, CutHeight)
					, GraphicsUnit.Pixel
					);
				bmPhoto.Save(sImgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
				imgPhoto.Dispose();
				gbmPhoto.Dispose();
				bmPhoto.Dispose();
			}
			catch (Exception err)
			{
				throw err;
			}
		}
		#endregion

		#region 水印
		/// <summary>
		/// 生成水印，可按左上、左下、右上、右下、居中、透明度生成文件，只对jpeg或jpg格式有效！
		/// </summary>
		/// <param name="sourceFile">底图</param>
		/// <param name="sm">水印图文件流</param>
		/// <param name="local">位置：左上(1)、左下(2)、右上(3)、右下(4)、居中(5)</param>
		/// <param name="alpha">透明度(1-100)</param>
		/// <returns>bool,是否成功</returns>
		public static bool MakeWaterImage(string sourceFile, Stream sm, int local, int alpha)
		{
			bool result;

			if (!File.Exists(sourceFile)) //如果源图不存在
				return false;
			FileInfo fi = new FileInfo(sourceFile);
			//判断文件类型是否合法   
			if (fi.Extension.ToLower() != ".jpg" & fi.Extension.ToLower() != ".jpeg")
				return false;

			try
			{
				//原图
				Bitmap sImage = new Bitmap(sourceFile);
				int sWidth = sImage.Width;
				int sHeight = sImage.Height;

				//水印图
				Bitmap wImage = new Bitmap(Image.FromStream(sm));
				int wWidth = wImage.Width;
				int wHeight = wImage.Height;

				//make Graphics.
				Graphics g = Graphics.FromImage(sImage);
				int x; //临时变量
				int y; //监时变量
				int x1 = 0; //原图和水印图的宽度差,即开始绘图的X位置
				int y1 = 0; //原图和水印图的高度差,即开始绘图的Y位置
				int w = 0; //生成的水印图的宽度,即结束绘图的X位置
				int h = 0; //生成的水印图的高度,即结束绘图的Y位置
				int al; //alpha
				int rl; //Red
				int gl; //Green
				int bl; //Blue

				//校验透明度
				if (alpha < 1 || alpha > 100)
					al = 80;
				else
					al = alpha;
				if (sWidth > wWidth & sHeight > wHeight) //如果源图比水印图大
				{
					switch (local)
					{
						case 1: //左上
							x1 = 0;
							y1 = 0;
							break;

						case 2: //左下
							x1 = 0;
							if ((sHeight - wHeight) > 0) //源图比水印图高
								y1 = sHeight - wHeight;
							else
								y1 = sWidth;
							break;
						case 3: //右上
							y1 = 0;
							if ((sWidth - wWidth) > 0) // 源图比水印图宽
								x1 = sWidth - wWidth;
							else
								x1 = sWidth;
							break;
						case 4: //右下
							//计算高度
							if ((sHeight - wHeight) > 0) //源图比水印图高
								y1 = sHeight - wHeight;
							else
								y1 = sWidth;
							//计算宽度
							if ((sWidth - wWidth) > 0) // 源图比水印图宽
								x1 = sWidth - wWidth;
							else
								x1 = sWidth;
							break;
						case 5: //居中
							//计算高度
							if ((sHeight - wHeight) > 0) //源图比水印图高
								y1 = (sHeight - wHeight) / 2;
							else
								y1 = sWidth;
							//计算宽度
							if ((sWidth - wWidth) > 0) // 源图比水印图宽
								x1 = (sWidth - wWidth) / 2;
							else
								x1 = sWidth;
							break;
					}
					if ((sHeight - wHeight) > 0)
						h = wHeight;
					else
						h = sHeight;
					if ((sWidth - wWidth) > 0)
						w = wWidth;
					else
						w = sWidth;
				}
				else //源图比水印图小
				{
					x1 = 0;
					y1 = 0;
					w = sWidth;
					h = sHeight;
				}

				//开始绘图
				for (x = 1; x < w; x++)
				{
					for (y = 1; y < h; y++)
					{
						al = alpha;
						rl = wImage.GetPixel(x, y).R;
						gl = wImage.GetPixel(x, y).G;
						bl = wImage.GetPixel(x, y).B;
						al = 70;

						if (rl + 25 < 255)
							rl += 25;
						if (gl + 25 < 255)
							gl += 25;
						if (bl + 25 < 255)
							bl += 25;
						g.DrawEllipse(new Pen(new SolidBrush(Color.FromArgb(al, rl, gl, bl))), x1 + x, y1 + y, 1, 1);
					}
				}
				g.Save();
				System.IO.File.Delete(sourceFile);
				sImage.Save(sourceFile);
				result = true;

			}
			catch
			{
				result = false;
			}
			return result;
		}

		/// <summary>
		/// 绘制水印
		/// </summary>
		/// <param name="ModifyImagePath">要修改的图像路径</param>
		/// <param name="sm">水印图文件流</param>
		/// <param name="RightSpace">水印在修改图片中的右边距</param>
		/// <param name="BottoamSpace">水印在修改图片中距底部的高度</param>
		/// <param name="LucencyPercent">要绘制水印的透明度,注意是原来图片透明度的百分比</param>
		/// <returns></returns>
		public static bool DrawWaterImage(
			string ModifyImagePath,
			Stream sm,
			int RightSpace,
			int BottoamSpace,
			int LucencyPercent)
		{
			bool IsSuccess = false;
			Image modifyImage = null;
			Image drawedImage = null;
			Graphics g = null;
			Bitmap gifImg = null;
			MemoryStream ms = null;
			FileStream fs = null;

			try
			{
				//建立图形对象
				modifyImage = Image.FromFile(ModifyImagePath);
				drawedImage = Image.FromStream(sm);

				g = Graphics.FromImage(modifyImage);

				//获取要绘制图形坐标
				int x = modifyImage.Width - RightSpace;
				int y = modifyImage.Height - BottoamSpace;
				//设置颜色矩阵
				float[][] matrixItems ={
										   new float[] {1, 0, 0, 0, 0},
										   new float[] {0, 1, 0, 0, 0},
										   new float[] {0, 0, 1, 0, 0},
										   new float[] {0, 0, 0, (float)LucencyPercent/100f, 0},
										   new float[] {0, 0, 0, 0, 1}};

				ColorMatrix colorMatrix = new ColorMatrix(matrixItems);
				ImageAttributes imgAttr = new ImageAttributes();
				imgAttr.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
				//绘制阴影图像
				g.DrawImage(
					drawedImage,
					new Rectangle(x, y, drawedImage.Width, drawedImage.Height),
					0, 0, drawedImage.Width, drawedImage.Height,
					GraphicsUnit.Pixel, imgAttr);
				//保存文件
				string[] allowImageType = { ".jpg", ".gif", ".png", ".bmp", ".tiff", ".wmf", ".ico" };
				FileInfo file = new FileInfo(ModifyImagePath);
				ImageFormat imageType = ImageFormat.Gif;
				switch (file.Extension.ToLower())
				{
					case ".jpg":
						imageType = ImageFormat.Jpeg;
						break;
					case ".gif":
						imageType = ImageFormat.Gif;
						break;
					case ".png":
						imageType = ImageFormat.Png;
						break;
					case ".bmp":
						imageType = ImageFormat.Bmp;
						break;
					case ".tif":
						imageType = ImageFormat.Tiff;
						break;
					case ".wmf":
						imageType = ImageFormat.Wmf;
						break;
					case ".ico":
						imageType = ImageFormat.Icon;
						break;
					default:
						break;
				}

				ms = new MemoryStream();

				#region 保存
				if (imageType.Equals(System.Drawing.Imaging.ImageFormat.Gif))
				{
					OctreeQuantizer qtz = new OctreeQuantizer(255, 8);
					gifImg = qtz.Quantize(modifyImage);

					gifImg.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
					gifImg.Dispose();
				}
				else
				{
					//设置 原图片 对象的 EncoderParameters 对象
					EncoderParameters parameters = new EncoderParameters();
					long[] quality = new long[1];
					quality[0] = 100;
					parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);

					ImageCodecInfo ici = GetCodecInfo((string)htmimes[file.Extension]);
					if (ici != null)
						modifyImage.Save(ms, ici, parameters);
					else
						modifyImage.Save(ms, imageType);

					parameters.Dispose();
				}
				#endregion

				byte[] imgData = ms.ToArray();
				modifyImage.Dispose();
				drawedImage.Dispose();
				g.Dispose();
				ms.Dispose();

				File.Delete(ModifyImagePath);
				fs = new FileStream(ModifyImagePath, FileMode.Create, FileAccess.Write);

				if (fs != null)
				{
					fs.Write(imgData, 0, imgData.Length);
					fs.Close();
				}
				IsSuccess = true;
			}
			finally
			{
				try
				{
					if (drawedImage != null)
						drawedImage.Dispose();
					if (gifImg != null)
						gifImg.Dispose();
					if (modifyImage != null)
						modifyImage.Dispose();
					if (g != null)
						g.Dispose();
					if (ms != null)
						ms.Dispose();
					if (fs != null)
						fs.Close();
				}
				catch
				{
				}
			}
			return IsSuccess;
		}

		/// <summary>
		/// 绘制水印
		/// </summary>
		/// <param name="ModifyImagePath">要修改的图像路径</param>
		/// <param name="DrawedImagePath">用来做水印的图片路径</param>
		/// <param name="RightSpace">水印在修改图片中的右边距</param>
		/// <param name="BottoamSpace">水印在修改图片中距底部的高度</param>
		/// <param name="LucencyPercent">要绘制水印的透明度,注意是原来图片透明度的百分比</param>
		/// <param name="OutPath">要输出图像的路径</param>
		/// <returns></returns>
		public static bool DrawWaterImage(
			string ModifyImagePath,
			string DrawedImagePath,
			int RightSpace,
			int BottoamSpace,
			int LucencyPercent,
			string OutPath)
		{
			bool IsSuccess = false;
			Image modifyImage = null;
			Image drawedImage = null;
			Graphics g = null;
			MemoryStream ms = null;
			FileStream fs = null;

			try
			{
				//建立图形对象
				modifyImage = Image.FromFile(ModifyImagePath);
				drawedImage = Image.FromFile(DrawedImagePath);
				g = Graphics.FromImage(modifyImage);

				//获取要绘制图形坐标
				int x = modifyImage.Width - RightSpace;
				int y = modifyImage.Height - BottoamSpace;
				//设置颜色矩阵
				float[][] matrixItems ={
										   new float[] {1, 0, 0, 0, 0},
										   new float[] {0, 1, 0, 0, 0},
										   new float[] {0, 0, 1, 0, 0},
										   new float[] {0, 0, 0, (float)LucencyPercent/100f, 0},
										   new float[] {0, 0, 0, 0, 1}};

				ColorMatrix colorMatrix = new ColorMatrix(matrixItems);
				ImageAttributes imgAttr = new ImageAttributes();
				imgAttr.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
				//绘制阴影图像
				g.DrawImage(
					drawedImage,
					new Rectangle(x, y, drawedImage.Width, drawedImage.Height),
					0, 0, drawedImage.Width, drawedImage.Height,
					GraphicsUnit.Pixel, imgAttr);
				//保存文件
				string[] allowImageType = { ".jpg", ".gif", ".png", ".bmp", ".tiff", ".wmf", ".ico" };
				FileInfo file = new FileInfo(ModifyImagePath);
				ImageFormat imageType = ImageFormat.Gif;
				switch (file.Extension.ToLower())
				{
					case ".jpg":
						imageType = ImageFormat.Jpeg;
						break;
					case ".gif":
						imageType = ImageFormat.Gif;
						break;
					case ".png":
						imageType = ImageFormat.Png;
						break;
					case ".bmp":
						imageType = ImageFormat.Bmp;
						break;
					case ".tif":
						imageType = ImageFormat.Tiff;
						break;
					case ".wmf":
						imageType = ImageFormat.Wmf;
						break;
					case ".ico":
						imageType = ImageFormat.Icon;
						break;
					default:
						break;
				}
				ms = new MemoryStream();
				modifyImage.Save(ms, imageType);
				byte[] imgData = ms.ToArray();
				modifyImage.Dispose();
				drawedImage.Dispose();
				g.Dispose();
				ms.Dispose();

				if (OutPath == null || OutPath == "")
				{
					File.Delete(ModifyImagePath);
					fs = new FileStream(ModifyImagePath, FileMode.Create, FileAccess.Write);
				}
				else
				{
					fs = new FileStream(OutPath, FileMode.Create, FileAccess.Write);
				}
				if (fs != null)
				{
					fs.Write(imgData, 0, imgData.Length);
					fs.Close();
				}
				IsSuccess = true;
			}
			finally
			{
				try
				{
					if (drawedImage != null)
						drawedImage.Dispose();
					if (modifyImage != null)
						modifyImage.Dispose();
					if (g != null)
						g.Dispose();
					if (ms != null)
						ms.Dispose();
					if (fs != null)
						fs.Close();
				}
				catch
				{
				}
			}
			return IsSuccess;
		}
		#endregion

		#region 文件检查
		/// <summary>
		/// 得到文件内容的文件类型
		/// </summary>
		/// <param name="content">文件内容</param>
		/// <returns>文件类型</returns>
		public static string GetFileClass(byte[] content)
		{
			string fileClass = string.Empty;
			if (content == null || content.Length < 2)
				return fileClass;

			return content[0].ToString().Trim() + "*" + content[1].ToString().Trim();
		}

		/// <summary>
		/// 检验文件是否正确
		/// </summary>
		/// <param name="fileClass"></param>
		/// <param name="Ext"></param>
		/// <returns>0:正常文件 1:可疑文件 2:禁止文件</returns>
		public static int CheckContent(string fileClass, string Ext)
		{
			if (fileClass == string.Empty)
				return 2;

			Ext = Ext.ToLower().Trim();
			if (Ext == ".jpg" && fileClass == "255*216")//255216是jpg
			{
				return 0;
			}
			else if (Ext == ".gif" && fileClass == "71*73")//7173是gif
			{
				return 0;
			}
			else if (Ext == ".bmp" && fileClass == "66*77")//6677是BMP
			{
				return 0;
			}
			else if (Ext == ".png" && fileClass == "137*80")//13780是PNG
			{
				return 0;
			}
			else if (fileClass == "77*90")//7790是exe
			{
				return 2;
			}
			else if (fileClass == "82*97")//8297是rar
			{
				return 2;
			}

			return 2;
		}

		/// <summary>
		/// 检验文件路径目录是否正确
		/// </summary>
		/// <param name="fileDirectory">文件路径目录</param>
		/// <returns>0:正常目录 1:可疑目录 2:禁止目录</returns>
		public static int CheckFilePath(string fileDirectory)
		{
			if (fileDirectory == string.Empty)
				return 2;

			fileDirectory = fileDirectory.Trim().ToLower();
			if (fileDirectory.LastIndexOf(".asp") >= 0 || fileDirectory.LastIndexOf(".asa") >= 0)
			{
				return 2;
			}
			else if (fileDirectory.LastIndexOf("@") >= 0)
			{
				return 1;
			}
			else if (fileDirectory.LastIndexOf("sasir") >= 0)
			{
				return 1;
			}
			return 0;
		}
		#endregion

		#region 灰度处理
		private void DrawForGrapMap(Bitmap image)
		{
			Graphics g = Graphics.FromImage(image);
			int Width = image.Width - 1;
			int Height = image.Height - 1;

			//绘制原图   
			g.DrawImage(image, 0, 0);
			g.TranslateTransform(image.Width, 0);

			/*image2、image3分别用来保存最大值法   
			和加权平均法处理的灰度图像*/
			Bitmap image2 = image.Clone(new Rectangle(0, 0, image.Width,
			image.Height), PixelFormat.DontCare);
			Bitmap image3 = image.Clone(new Rectangle(0, 0, image.Width,
			image.Height), PixelFormat.DontCare);

			Color color;
			//使用平均值进行灰度处理   
			for (int i = Width; i >= 0; i--)
				for (int j = Height; j >= 0; j--)
				{
					color = image.GetPixel(i, j);
					//求出平均三个色彩分量的平均值   
					int middle = (color.R +
					color.G + color.B) / 3;
					Color colorResult = Color.FromArgb(255, middle, middle, middle);
					image.SetPixel(i, j, colorResult);
				}
			//重新绘制灰度化图   
			g.DrawImage(
			image, new Rectangle(0, 0, Width, Height));

			//在新位置显示最大值法进行灰度处理的结果   
			g.TranslateTransform(image.Width, 0);
			//使用最大值法进行灰度处理   
			for (int i = Width; i >= 0; i--)
			{
				for (int j = Height; j >= 0; j--)
				{
					color = image2.GetPixel(i, j);
					int tmp = Math.Max(color.R, color.G);
					int maxcolor = Math.Max(tmp, color.B);
					Color colorResult = Color.FromArgb(255, maxcolor, maxcolor, maxcolor);
					//设置处理后的灰度信息   
					image2.SetPixel(i, j, colorResult);
				}
			}

			//重新绘制灰度化图   
			g.DrawImage(
			image2, new Rectangle(0, 0, Width, Height));
			//在第二行绘制图片   
			g.ResetTransform();
			g.TranslateTransform(0, image.Height);

			//使用加权平均法进行灰度处理   
			for (int i = Width; i >= 0; i--)
			{
				for (int j = Height; j >= 0; j--)
				{
					color = image3.GetPixel(i, j);
					int R = (int)(0.3f * color.R);
					int G = (int)(0.59f * color.G);
					int B = (int)(0.11f * color.B);

					Color colorResult = Color.FromArgb(255, R, G, B);
					//设置处理后的灰度信息   
					image3.SetPixel(i, j, colorResult);
				}
			}
			//重新绘制灰度化图   
			g.DrawImage(
			image3, new Rectangle(0, 0, Width, Height));

			g.TranslateTransform(image.Width, 0);
			//灰度的还原演示，还原使用最大值法处理的灰度图像image2   
			for (int i = Width; i > 0; i--)
			{
				for (int j = Height; j > 0; j--)
				{
					color = image2.GetPixel(i, j);
					int R = color.R;
					int G = color.G;
					int B = color.B;
					//分别对RGB三种色彩分量进行伪彩色还原   

					//进行红色分量的还原   
					if (R < 127)
						R = 0;
					if (R >= 192)
						R = 255;
					if (R <= 191 && R >= 128)
						R = 4 * R - 510;

					/*进行绿色分量的还原,为了还原后的绿色分量再次参加比较，   
					这里设置一个变量YES表示G是否已经参加了比较*/

					bool yes;
					yes = false;
					if (G <= 191 && G >= 128 && (!yes))
					{
						G = 255;
						yes = true;
					}
					if (G >= 192 && (!yes))
					{
						G = 1022 - 4 * G;
						yes = true;
					}
					if (G <= 63 && (!yes))
					{
						G = 254 - 4 * G;
						yes = true;
					}
					if (G <= 127 && G >= 67 && (!yes))
						G = 4 * G - 257;

					//进行蓝色分量的还原   
					if (B <= 63)
						B = 255;
					if (B >= 128)
						B = 0;
					if (B >= 67 && B <= 127)
						B = 510 - 4 * B;

					//还原后的伪彩色   
					Color colorResult = Color.FromArgb(255, R, G, B);
					//将还原后的RGB信息重新写入位图   
					image2.SetPixel(i, j, colorResult);

				}
			}
			//重新绘制还原后的伪彩色位图   
			//重新绘制灰度化图   
			g.DrawImage(image2, new Rectangle(0, 0, Width, Height));
		}

		
		/// <summary>
		/// ConvertStreamToByteBuffer：把给定的文件流转换为二进制字节数组。
		/// </summary>
		/// <param name="theStream"></param>
		/// <returns></returns>
		public static byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream)
		{
			int b1;
			System.IO.MemoryStream tempStream = new System.IO.MemoryStream();
			while ((b1 = theStream.ReadByte()) != -1)
			{
				tempStream.WriteByte(((byte)b1));
			}
			return tempStream.ToArray();
		}

		#endregion
	}
}
